<template>
    <div class="container">
        <el-page-header @back="goBack" content="默认价格"></el-page-header>
        <!-- 分类 -->
        <div class="type-state e-m-t-45 e-m-b-30">
            <span class="e-p-l-30 e-p-r-30" v-for="(item, index) in statusArr" :key="index" :class="{ 'on': state == item.value }" @click="goPage(item.value)">{{ item.name }}</span>
        </div>
        <!-- <div>
            <el-button type="primary" icon="el-icon-plus" @click="creadLargeType">新建类型</el-button>
        </div> -->
        <!-- 默认品类列表 -->
        <div class="type-list">
            <div class="left-box">
                <div class="item" v-for="(item, index) in list" :key="index" :class="{ 'on': index == chooseIndex }"
                    @click="chooseLargeType(item, index)">
                    <span>{{ item.name }}</span>
                </div>
            </div>
            <div class="right-box" v-if="list.length > 0">
                <div class="cell">
                    <!-- <h4 class="title-item">类型设置</h4> -->
                    <div class="breadcrumb-box flex">
                        <span style="font-size: 14px;line-height: 1;" class="tips">分类导航：</span>
                        <el-breadcrumb separator-class="el-icon-arrow-right" class="e-m-b-20">
                            <el-breadcrumb-item
                                v-for="(item, index) in breadcrumbList"
                                :key="index"
                                @click.native="handleBreadcrumbClick(item, index)"
                                :class="{ 'is-last': index === breadcrumbList.length - 1 }"
                            >
                                {{ item.name }}
                            </el-breadcrumb-item>
                        </el-breadcrumb>
                    </div>

                    <el-descriptions class="" title="" :column="5" direction="vertical" border>
                        <el-descriptions-item label="上级分类名称">
                            <div class="flex" style="align-items: center;">
                                <el-image style="width: 40px; height: 40px" :src="fileURL + categoryTypeObj.icon"
                                    fit="cover" v-if="pid == 0"></el-image>
                                <span class="e-p-l-5">{{ categoryTypeObj.name }}</span>
                            </div>
                        </el-descriptions-item>
                        <el-descriptions-item label="计算单位">{{ categoryTypeObj.isweighing ? '按重量' : '按件数'
                            }}</el-descriptions-item>
                        <el-descriptions-item label="排序">{{ categoryTypeObj.sort }}</el-descriptions-item>
                        <!-- <el-descriptions-item label="价格范围">0.2-1.8</el-descriptions-item> -->
                        <el-descriptions-item label="是否启用">
                            <el-switch v-model="categoryTypeObj.state" @change="switchState($event, categoryTypeObj.id,true)"></el-switch>
                        </el-descriptions-item>
                        <el-descriptions-item label="操作">
                            <el-button @click="getSmallTypeList(scope.row, scope.row.id)" type="text" size="small">查看下级</el-button>
                            <el-button @click="edit(categoryTypeObj)" type="text" size="small">编辑</el-button>
                            <el-button @click="del(categoryTypeObj.id)" type="text" size="small">删除</el-button>
                        </el-descriptions-item>
                    </el-descriptions>

                    <h4 class="title-item">{{ categoryTypeObj.name }}下级和价格设置</h4>
                    <el-row type="flex" justify="space-between">
                        <!-- <el-col :span="3">
                            <el-button type="primary" icon="el-icon-plus" @click="creadSmallType">新建{{ categoryTypeObj.name }}下级</el-button>
                        </el-col> -->
                        <el-col class="text-right">
                            <el-form :inline="true"  class="nav-bar-form">
                                <el-form-item>
                                    <el-input placeholder="关键词搜索" v-model="key" clearable prefix-icon="el-icon-search" @clear="getSmallTypeList(categoryTypeObj,pid,true)"></el-input>
                                </el-form-item>
                                <el-form-item>
                                    <el-button type="primary" @click="getSmallTypeList(categoryTypeObj,pid,true)">查询</el-button>
                                </el-form-item>
                            </el-form>
                        </el-col>
                    </el-row>

                    <el-table :data="tableData" stripe>
                        <el-table-column label="下级名称" prop="name"></el-table-column>
                        <el-table-column label="上门回收价格" prop="onsiteprice"></el-table-column>
                        <el-table-column label="站点回收价格" prop="storeprice"></el-table-column>
                        <el-table-column label="打包站回收价格" prop="packprice"></el-table-column>
                        <el-table-column prop="isweighing" label="客户组">
                            <template slot-scope="scope">
                                <span>{{ scope.row.isweighing == true?'KG':'件' }}</span>
                            </template>
                        </el-table-column>
                        <el-table-column label="排序" prop="sort"></el-table-column>
                        <el-table-column label="是否启用">
                            <template slot-scope="scope">
                                <el-switch v-model="scope.row.state" @change="switchState($event, scope.row.id)"></el-switch>
                            </template>
                        </el-table-column>
                        <el-table-column label="操作">
                            <template slot-scope="scope">
                                <!-- <el-button @click="getSmallTypeList(scope.row, scope.row.id)" type="text" size="small">查看下级</el-button> -->
                                <el-button @click="editSmallType(scope.row)" type="text" size="small">编辑</el-button>
                                <el-button @click="delSmallType(scope.row.id)" type="text" size="small">删除</el-button>
                                <!-- <el-button type="text" size="small">设置价格</el-button> -->
                            </template>
                        </el-table-column>
                    </el-table>
                </div>
            </div>
        </div>
        <!-- 新建或编辑分类 -->
        <el-dialog :title="dialogType == 'add' ? '新建分类' : '编辑分类'" :visible.sync="dialogVisible" width="800px" @close="cancel">
            <el-form ref="form" :model="createdType" :rules="rules" label-width="180px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="createdType.name"></el-input>
                </el-form-item>
                <el-form-item label="描述" prop="brief">
                    <el-input v-model="createdType.brief"></el-input>
                </el-form-item>
                <el-form-item label="上传图标" prop="icon">
                    <cropper-upload :zoomScale='[1, 1]' :isCropper="true" @getUpload="handleFilesSuccess"
                        class="avatar-uploader">
                        <img v-if="createdType.icon" :src="fileURL + createdType.icon" class="avatar">
                        <div class="avatar-uploader-icon" v-else>
                            <div><i class="el-icon-plus"></i></div>
                            <div class="e-font-14">上传图片</div>
                        </div>
                    </cropper-upload>
                    <div class="tips">建议上传尺寸比例为200*200 </div>
                </el-form-item>
                <el-form-item label="计算单位">
                    <el-radio-group v-model="createdType.isweighing">
                        <el-radio :label="true">按重量(KG)</el-radio>
                        <el-radio :label="false">按数量(件)</el-radio>
                    </el-radio-group>
                </el-form-item>
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancel">取消</el-button>
                <el-button type="primary" @click="submitType">{{ dialogType == 'add' ? '添加' : '修改'}}</el-button>
            </span>
        </el-dialog>
        <!-- 新建或编辑小类 -->
        <el-dialog :title="editDialogType == 'add' ? `新建${categoryTypeObj.name}下属可回收物` : `编辑${categoryTypeObj.name}下属可回收物`" :visible.sync="editDialogVisible" width="800px" @close="cancel">
            <el-form ref="smallTypeForm" :model="smallTypeObj" :rules="rules" label-width="180px">
                <el-form-item label="名称" prop="name">
                    <el-input v-model="smallTypeObj.name"></el-input>
                </el-form-item>
                <el-form-item label="减碳量百分比" prop="carbon">
                    <el-input v-model="smallTypeObj.carbon"></el-input>
                </el-form-item>
                <el-form-item label="排序" prop="sort">
                    <el-input v-model="smallTypeObj.sort"></el-input>
                </el-form-item>
                <el-form-item label="默认上门价" prop="onsiteprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.onsiteprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="smallTypeObj.onsiteprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="smallTypeObj.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.onsiteprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="smallTypeObj.onsiteprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.onsiteprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="默认站点价" prop="storeprice">
					<div class="flex" style="align-items: center;">
						<el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.storeprice.price">
							<template slot="prepend">价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
						<el-switch v-model="smallTypeObj.storeprice.edit" active-text="允许修改"></el-switch>
					</div>
                    <div class="flex e-m-b-15 e-m-t-15" style="align-items: center;" v-if="smallTypeObj.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.storeprice.minprice">
							<template slot="prepend">允许修改最低价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
                    <div class="flex" style="align-items: center;" v-if="smallTypeObj.storeprice.edit">
                        <el-input
							type="number"
							class="e-flex-1 e-m-r-10" style="align-items: center"
							v-model="smallTypeObj.storeprice.highprice">
							<template slot="prepend">允许修改最高价格</template>
							<span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
						</el-input>
                    </div>
				</el-form-item>
                <el-form-item label="预估出库价" prop="packprice">
                    <el-input v-model="smallTypeObj.packprice">
                        <span slot="suffix" class="el-input__icon">元/{{ smallTypeObj.isweighing?'公斤':'件' }}</span>
                    </el-input>
                </el-form-item>
                <el-form-item label="按件估重 （选填）" prop="estimatedweight">
                    <el-input v-model="smallTypeObj.estimatedweight"></el-input>
                </el-form-item>
                <el-form-item label="备注" prop="remarks">
                    <el-input v-model="smallTypeObj.remarks" type="textarea"></el-input>
                </el-form-item>
                <!-- <el-form-item label="上传图标" prop="icon">
                    <cropper-upload :zoomScale='[1, 1]' :isCropper="true" @getUpload="handleFilesSuccess"
                        class="avatar-uploader">
                        <img v-if="smallTypeObj.icon" :src="fileURL + smallTypeObj.icon" class="avatar">
                        <div class="avatar-uploader-icon" v-else>
                            <div><i class="el-icon-plus"></i></div>
                            <div class="e-font-14">上传图片</div>
                        </div>
                    </cropper-upload>
                    <div class="tips">建议上传尺寸比例为200*200 </div>
                </el-form-item> -->
            </el-form>
            <span slot="footer" class="dialog-footer">
                <el-button @click="cancelSmallType">取消</el-button>
                <el-button type="primary" @click="submitSmallType(smallTypeObj)">{{ editDialogType == 'add' ? '添加' : '确定修改'}}</el-button>
            </span>
        </el-dialog>
    </div>
</template>

<script>
// import {
// 	mapState
// } from 'vuex';

export default {
    layout: 'admin',
    head() {
        return {
            title: '默认价格'
        }
    },
    data() {
        return {
            loading: false,
            pageIndex: 1,
            pageSize: 999,
            total: 0,
            key: '',
            statusArr: [
                {
                    name: '默认价格',
                    value: 1
                },
                {
                    name: '上门价',
                    value: 2
                },
                {
                    name: '站点价',
                    value: 3
                },
                {
                    name: '客户组价',
                    value: 4
                }
            ],
            breadcrumbList: [

            ], // 面包屑导航数组
            state: 1,
            list: [],
            chooseIndex: 0,
            tableData: [],
            typeId: 0, //类型id
            pid: 0, //下级分类id
            // 新建或编辑类型
            dialogVisible: false,
            dialogType: 'add',
            categoryTypeObj: {
                icon: ""
            },
            createdType: {
                name: "",
                brief: "",
                smallicon: "",
                icon: "",
                isWeighing: true
            },
            rules: {
                name: [{
                    required: true,
                    message: '请填写废品分类名称',
                    trigger: 'blur'
                }],
                icon: [{
                    required: true,
                    message: '请填写图标名称',
                    trigger: 'blur'
                }],
            },
            // 新建或编辑小类
            editDialogType: 'add',
            editDialogVisible: false,
            smallTypeObj:{
                "typeId":0,
                "id": 0,
                "name": "",
                "carbon": null,
                "pic": "",
                "sort": null,
                "packprice": null,
                "isweighing": true,
                "onsiteprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "storeprice": {
                    "edit": true,
                    "price": null,
                    "minprice": null,
                    "highprice": null
                },
                "estimatedweight": null
            }
        }
    },
    // computed: {
    //     ...mapState({
	// 		operatorid: state => state.operatorid,
	// 	})
    // },
    watch:{
        editDialogVisible(val){
            if(!val){
                this.smallTypeObj = {
                    "typeId":0,
                    "id": 0,
                    "name": "",
                    "carbon": null,
                    "pic": "",
                    "sort": null,
                    "packprice": null,
                    "isweighing": true,
                    "onsiteprice": {
                        "edit": true,
                        "price": null,
                        "minprice": null,
                        "highprice": null
                    },
                    "storeprice": {
                        "edit": true,
                        "price": null,
                        "minprice": null,
                        "highprice": null
                    },
                    "estimatedweight": null
                }
            }
        }
    },
    mounted() {
        console.log('默认价格')
        this.getList().then(() => {
            this.chooseLargeType(this.list[0], 0)
        })
    },
    methods: {
        // 返回上一页
        goBack() {
            this.$router.go(-1)
        },
        // 跳转页面
        goPage(value){
            switch(value){
                case 1:
                    this.$router.push(`/price/default`)
                    break
                case 2:
                    this.$router.push(`/price/onsite`)
                    break
                case 3:
                    this.$router.push(`/price/store`)
                    break
                case 4:
                    this.$router.push(`/price/enterprise`)
                    break
            }
        },
        // 点击面包屑项
        handleBreadcrumbClick(item, index) {
            // 点击的不是最后一项时才允许跳转
            if(index < this.breadcrumbList.length - 1) {
                // 如果是根节点
                if(index === 0) {
                    this.chooseLargeType(this.list[0], 0)
                    this.breadcrumbList = this.breadcrumbList.slice(0, 1)
                } else {
                    // 这里需要根据你的接口实现获取父级数据
                    this.getSmallTypeList(item, item.pid)
                    this.breadcrumbList = this.breadcrumbList.slice(0, index + 1)
                }
            }
        },
        // 获取类型
        getList() {
            this.list = []
            return this.$axios.get(`/Waste/Type/List`).then((res) => {
                this.loading = false
                let datas = res
                datas.forEach((item) => {
                    if (item.usestate == '已启用') {
                        item.state = true
                    } else {
                        item.state = false
                    }
                })
                this.list = datas;
            }).catch(() => {
                this.loading = false
            })
        },
        //修改状态
        switchState(event, id, isLargeType = false) {
            let api = ''
            if(isLargeType){
                api = '/Waste/Type/SetState'
            }else{
                api = '/Waste/product/SetState'
            }
            this.$axios.post(api, {
                ids: [id],
                state: event ? '已启用' : '已冻结'
            }).then((res) => {
                if (res.status == 0) {
                    this.$message.success(res.msg);
                } else {
                    this.$message.error(res.msg);
                }
            }).catch((err) => {
                this.getList()
            })
        },
        // 选择类型
        chooseLargeType(item,index){
            this.typeId = item.id
            this.chooseIndex = index
            this.getSmallTypeList(item)
            this.breadcrumbList = [{
                ...item
            }]
        },
        // 获取小类
        getSmallTypeList(categoryTypeObj, pid = 0, isSearch = false) {
            // 当进入下级时更新面包屑
            if(pid > 0 && isSearch == false) {
                if(this.breadcrumbList.filter((item)=>item.id == categoryTypeObj.id).length == 0){
                    if(categoryTypeObj.pid == this.breadcrumbList[this.breadcrumbList.length - 1].pid){
                        this.breadcrumbList.splice(this.breadcrumbList.length - 1, 1)
                    }
                    this.breadcrumbList.push({
                        ...categoryTypeObj
                    })
                }
            }
            this.tableData = []
            this.loading = true
            this.categoryTypeObj = categoryTypeObj
            this.pid = pid
            let api = ''
            if(this.pid > 0){
                api = `/Waste/product/List?typeId=${this.typeId}&pid=${this.pid}&Key=${this.key}`
            }else{
                api = `/Waste/product/List?typeId=${this.typeId}&Key=${this.key}`
            }
            this.$axios.get(api).then((res) => {
                let datas = res.sort((a, b) => a.sort - b.sort)
                datas.forEach((item) => {
                    if (item.usestate == '已启用') {
                        item.state = true
                    } else {
                        item.state = false
                    }
                })
                this.tableData = datas;
                this.total = res.total;
                this.loading = false
            }).catch(() => {
                this.loading = false
            })
        },
        // 创建类型
        creadLargeType() {
            this.dialogType = 'add'
            this.dialogVisible = true
            this.createdType = {
                name: "",
                brief: "",
                smallicon: "",
                icon: "",
                isWeighing: true,
            }
        },
        // 取消创建或编辑类型
        cancel() {
            this.dialogVisible = false
        },
        // 删除类型
        del(id) {
            return new Promise((resolve, reject) => {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post('/Waste/Type/Delete?id=' + id).then((res) => {
                    	this.$message.success(res.msg);
                    	this.getList()
                    	resolve()
                    })
                })
            })
        },
        // 提交创建或修改类型
        submitType() {
            let api = ''
            if (this.dialogType == 'add') {
                api = '/Waste/Type/Create'
            }
            if (this.dialogType == 'edit') {
                api = '/Waste/Type/Edit'
            }

            this.$refs.form.validate((valid) => {
                if (valid) {
                    this.$axios.post(api, this.createdType).then((res) => {
                        this.$message.success(res.msg);
                        this.dialogVisible = false;
                        this.getList()
                    }).catch(() => {

                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
        // 上传图标
        handleFilesSuccess(res, file) {
            console.log(res,file)
            if (file.status === "success") {
                this.loading = false
                this.createdType.icon = res.path
            }
        },
        creadSmallType(){
            this.editDialogType = 'add'
            this.editDialogVisible = true
        },
        edit(obj){
            this.dialogType = 'edit'
            this.dialogVisible = true
            this.createdType = obj
        },
        // 编辑小类
        editSmallType(obj){
            this.editDialogType = 'edit'
            this.editDialogVisible = true

            this.smallTypeObj = {
                id: obj.id,
                typeid: obj.typeid,
                name: obj.name,
                carbon: obj.carbon,
                isweighing: obj.isweighing,
                // pic: "",
                sort: obj.sort,
                packprice: obj.packprice,
                onsiteprice: {
                    edit: obj.editonsiteprice,
                    price: obj.onsiteprice,
                    minprice: obj.onsiteminprice,
                    highprice: obj.onsitehighprice
                },
                storeprice: {
                    edit: obj.editstoreprice,
                    price: obj.storeprice,
                    minprice: obj.storeminprice,
                    highprice: obj.storehighprice
                },
                estimatedweight: obj.estimatedweight,
                remarks: obj.remarks,
                usestate: obj.usestate
            }
        },
        // 删除小类
        delSmallType(id) {
            return new Promise((resolve, reject) => {
                this.$confirm('此操作将删除该数据, 是否继续?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning'
                }).then(() => {
                    this.$axios.post('/Waste/product/Delete?id=' + id).then((res) => {
                    	this.$message.success(res.msg);
                    	this.getSmallTypeList(this.categoryTypeObj,this.pid)
                    	resolve()
                    })
                })
            })
        },
        // 取消创建或编辑小类
        cancelSmallType() {
            this.editDialogVisible = false
        },
        removeEmpty(obj) {
            const clean = (value) => {
                if (value === null || value === undefined) return undefined;
                if (typeof value === 'string' && value.trim() === '') return undefined;
                if (Array.isArray(value)) {
                    return value.map(clean).filter(item => item !== undefined);
                }
                if (typeof value === 'object') {
                    const result = {};
                    Object.keys(value).forEach(key => {
                        const cleaned = clean(value[key]);
                        if (cleaned !== undefined) result[key] = cleaned;
                    });
                    return Object.keys(result).length ? result : undefined;
                }
                return value;
            };
            return clean(obj) || {};
        },
        // 提交创建或修改小类
        submitSmallType() {
            let api = ''
			if (this.editDialogType == 'add') {
				api = '/Waste/product/Create'
                this.smallTypeObj.typeId = this.typeId
                this.smallTypeObj.pid = this.pid
			}
			if (this.editDialogType == 'edit') {
				api = '/Waste/product/Edit'
			}
            this.$refs.smallTypeForm.validate((valid) => {
                if (valid) {
                    // 过滤空值参数
                    const cleanedData = this.removeEmpty(this.smallTypeObj);
                    this.$axios.post(api, cleanedData).then((res) => {
                        this.$message.success(res.msg);
                        this.editDialogVisible = false;
                        this.getSmallTypeList(this.categoryTypeObj,this.pid)
                    }).catch(() => {

                    })
                } else {
                    console.log('error submit!!');
                    return false;
                }
            });
        },
    }
}
</script>

<style lang="scss" scoped>
    // .el-breadcrumb {
    //     margin-bottom: 20px;
    //     .el-breadcrumb__item {
    //         cursor: pointer;
    //         &:hover {
    //             color: var(--main);
    //         }
    //         &.is-last {
    //             cursor: default;
    //             color: #999;
    //             &:hover {
    //                 color: #999;
    //             }
    //         }
    //     }
    // }
    //默认品类列表
    .type-list {
        margin-top: 15px;
        display: flex;
        min-height: calc(100vh - 341px);

        .left-box {
            .item {
                // display: inline-block;
                width: 150px;
                height: 50px;
                // line-height: 40px;
                text-align: center;
                // border: 1px solid #e6e6e6;
                // margin-right: 10px;
                margin-bottom: 10px;
                display: flex;
                align-items: center;
                justify-content: center;
                cursor: pointer;

                &:last-child {
                    margin-bottom: 0;
                }

                &:hover {
                    background: #f7f8fa;
                }

                &.on {
                    background-color: #02d5d61f;

                    span {
                        color: var(--main);
                        border-left: 3px solid var(--main);
                        display: block;
                        line-height: 1.4em;
                        width: 100%;
                    }
                }
            }
        }

        .right-box {
            // flex: 1;
            background: #f7f8fa;
            padding: 15px;
            width: calc(100vw - 490px);

            .cell {
                background-color: #fff;
                padding: 30px;
                border-radius: 5px;
                min-height: 100%;
                box-sizing: border-box;
                box-shadow: 0 0 16px 0 rgb(0 0 0 / 4%);

                .title-item {
                    // background: #f7f8fa;
                    // color: var(--grey);
                    // padding: 10px;
                }
            }
        }
    }
</style>
